#include "PapaObject.h"
#include "utility.h"
using namespace Ogre;

PapaObject::PapaObject()
{
	mSpeed = 0;
	mAngleSpeed = 0;
	mInfinite = true;
	mDirection=Vector3::ZERO;
}

Ogre::SceneNode* PapaObject::getNode()
{
	return mAttachedSceneNode;
}

Vector3 PapaObject::getPostion()
{
	return mAttachedSceneNode->getPosition();
}

Ogre::Quaternion PapaObject::getOrientation()
{
	return mAttachedSceneNode->getOrientation();
}

void PapaObject::setPostion( Ogre::Vector3 pos )
{
	mAttachedSceneNode->setPosition(pos);
}

void PapaObject::setOrientation( Ogre::Quaternion ort )
{
	mAttachedSceneNode->setOrientation(ort);
}

void PapaObject::setSpeed(Ogre::Real speed)
{
	mSpeed = speed;
}

Ogre::Real PapaObject::getSpeed()
{
	return mSpeed;
}

void PapaObject::AddTime( Ogre::Real time )
{
	_UpdatePostion(time);
}

void PapaObject::setTargetPostion( Ogre::Vector3 des )
{
	mDirection = des - mAttachedSceneNode->getPosition();
	mDistanceLeft = mDirection.length();
	mDirection.normalise();
	mInfinite = false;
}

void PapaObject::setTargetOrientation( Ogre::Quaternion desOrt, Ogre::Real transTime )
{
	Ogre::Quaternion nowOrt = getOrientation();
	Ogre::Quaternion rot = (nowOrt.Inverse()*desOrt);
	rot.ToAngleAxis(mAngleLeft, mRotateAxis);
	Ogre::Quaternion fuck = nowOrt*rot;
	mAngleSpeed = mAngleLeft/transTime;
}

void PapaObject::_UpdatePostion( Ogre::Real time )
{
	if (!equal(mSpeed,0))
	{
		Ogre::Real movedDistance;
		if (mInfinite)
		{
			movedDistance = mSpeed*time;
		} 
		else
		{
			if (mDistanceLeft-mSpeed*time<0)
			{
				movedDistance = mDistanceLeft;
			}
			else movedDistance = mSpeed*time;
			mDistanceLeft -= movedDistance;
		}
		setPostion(mAttachedSceneNode->getPosition()+mDirection*movedDistance);
		if (equal(mDistanceLeft,0))
		{
			mSpeed = 0;
		}
	}

	if (!equal(mAngleSpeed.valueRadians(),0))
	{
		Ogre::Radian rotatedAngle;
		if ((mAngleLeft-mAngleSpeed*time).valueRadians()<0)
		{
			rotatedAngle=mAngleLeft;
		}
		else rotatedAngle=mAngleSpeed*time;
		mAngleLeft -= rotatedAngle;
		Ogre::Quaternion t(rotatedAngle, mRotateAxis);
		mAttachedSceneNode->rotate(t);
		//PRINT(mAttachedSceneNode->getOrientation());
		//setOrientation(mAttachedSceneNode->getOrientation()*t);
		if (equal(mAngleLeft.valueRadians(),0)) mAngleSpeed = 0;
	}
}

Ogre::Vector3 PapaObject::getDirection()
{
	if (equal(mSpeed,0))
	{
		return Ogre::Vector3::ZERO;
	} 
	else
	{
		return mDirection;
	}
}

void PapaObject::setDirection( Ogre::Vector3 dir )
{
	mDirection = dir;
	mInfinite = true;
}

bool PapaObject::IsMoving()
{
	return mDirection!=Vector3::ZERO;
}



